package com.imooc.service.impl;

import com.imooc.bo.SubmitOrderBo;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.*;
import com.imooc.pojo.*;
import com.imooc.service.ItemService;
import com.imooc.service.OrderService;
import com.imooc.utils.DateUtil;
import com.imooc.vo.MerchantOrdersVO;
import com.imooc.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.annotation.Order;

import java.util.Date;
import java.util.List;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2022-03-29 18:52
 */
@Service
@Slf4j
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private ItemsSpecMapper itemsSpecMapper;
    @Autowired
    private ItemsImgMapper itemsImgMapper;
    @Autowired
    private Sid sid;
    @Autowired
    private ItemService itemService;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public OrderVO createOrder(SubmitOrderBo submitOrderBo) {
        String userId = submitOrderBo.getUserId();
        int sum = 0;
        int sumNormal = 0;
        String addressId = submitOrderBo.getAddressId();
        UserAddress userAddress = userAddressMapper.selectByPrimaryKey(addressId);
        String orderId = sid.nextShort();
        String itemSpecIds = submitOrderBo.getItemSpecIds();
        String[] specIdArr = itemSpecIds.split(",");
        for (String specId : specIdArr) {
            int byCount =1 ;
            ItemsSpec itemsSpec = itemsSpecMapper.selectByPrimaryKey(specId);
            String mainImgUrl = itemService.getMainImgUrl(itemsSpec.getItemId());
            Integer priceDiscount = itemsSpec.getPriceDiscount();
            sum+=priceDiscount*byCount;
            sumNormal+=itemsSpec.getPriceNormal()*byCount;
            OrderItems orderItems = new OrderItems();
            orderItems.setOrderId(orderId);
            orderItems.setId(sid.nextShort());
            orderItems.setItemId(itemsSpec.getItemId());
            orderItems.setItemName(itemsSpec.getName());
            orderItems.setItemSpecName(itemsSpec.getName());
            orderItems.setItemSpecId(specId);
            orderItems.setBuyCounts(1);
            orderItems.setItemImg(mainImgUrl);
            orderItems.setPrice(priceDiscount);
            orderItemsMapper.insert(orderItems);
            // 扣除库存
            itemService.decreaseItemSpecStock(specId,byCount);
        }
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setCreatedTime(new Date());
        orders.setUpdatedTime(new Date());
        orders.setTotalAmount(sumNormal);
        orders.setUserId(userId);
        orders.setReceiverName(userAddress.getReceiver());
        orders.setReceiverMobile(userAddress.getMobile());
        orders.setReceiverAddress(userAddress.getDetail());
        orders.setRealPayAmount(sum);
        orders.setPostAmount(0);
        orders.setPayMethod(submitOrderBo.getPayMethod());
        orders.setLeftMsg(submitOrderBo.getLeftMsg());
        orders.setIsDelete(YesOrNo.NO.getCode());
        orders.setIsComment(YesOrNo.NO.getCode());
        orders.setExtand("");

        ordersMapper.insert(orders);
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setCreatedTime(new Date());
        orderStatus.setOrderId(orderId);
        orderStatus.setOrderStatus(OrderStatusEnum.TO_BE_PAYED.code);
        orderStatus.setCloseTime(new Date(System.currentTimeMillis()+7*24*3600*1000));
        orderStatusMapper.insert(orderStatus);

        //4. 构建商户订单
        MerchantOrdersVO vo = new MerchantOrdersVO();
        vo.setMerchantOrderId(orderId);
        vo.setMerchantUserId(userId);
        vo.setAmount(sum);
        vo.setPayMethod(submitOrderBo.getPayMethod());

        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(orderId);
        orderVO.setMerchantOrdersVO(vo);


        return orderVO;
    }

    /**
     * 修改订单状态
     * @param orderId
     * @param orderStatus
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public void updateOrderStatus(String orderId,Integer orderStatus) {
        OrderStatus orderStatus1 = new OrderStatus();
        orderStatus1.setOrderId(orderId);
        orderStatus1.setOrderStatus(orderStatus);
        orderStatus1.setPayTime(new Date());
        orderStatusMapper.updateByPrimaryKey(orderStatus1);
    }

    /**
     * 查询订单状态
     * @param orderId
     * @return
     */
    @Override
    public OrderStatus queryOrderInfo(String orderId) {
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        OrderStatus target = orderStatusMapper.selectOne(orderStatus);
        return target;
    }

    /**
     * 关闭超时未支付订单
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void closeOrder() {
        // 超时时间设置为1天, 关闭交易
        OrderStatus queryOrderStatus = new OrderStatus();
        queryOrderStatus.setOrderStatus(OrderStatusEnum.TO_BE_PAYED.code);

        List<OrderStatus> select = orderStatusMapper.select(queryOrderStatus);
        Date now = new Date();
        for (OrderStatus orderStatus : select) {
            Date createdTime = orderStatus.getCreatedTime();
            int days = DateUtil.daysBetween(createdTime, now);
            if(days>-1) {
                doCloseOrder(orderStatus.getOrderId(),now);
            }
        }

    }
    @Transactional(propagation = Propagation.REQUIRED)
    private void doCloseOrder(String orderId,Date date) {
        OrderStatus close = new OrderStatus();
        close.setOrderId(orderId);
        close.setOrderStatus(OrderStatusEnum.FAIL.code);
        close.setCloseTime(date);
        orderStatusMapper.updateByPrimaryKey(close);

    }
}
